/**
 * Created by shudong.msd(风骐) on 2016/4/17.
 */

"use strict";

app.controller('loginFormCtrl', ['$scope','$http','$state',function($scope,$http,$state) {
    $scope.formData={
        'username':'pmmtest',
        'password':'XsvF1KPYRW'
    };
    $scope.processForm = function(isValid) {
        if (!isValid) {
            //alert('验证失败');
            $scope.message = '密码或用户名不能为空！';
            return;
        }else{
            $scope.message = '';
        }
        angular.element('button[type="submit"]').attr('disabled','true');
        $http({
            method  : 'POST',
            url     : UrlMappings.LOGIN,
            data    : $.param($scope.formData),
            headers : {
                'Accept':'text/html',
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }).success(function(data) {
            var b64 = new Base64();
            //存储用户信息
            var userInfo = {'name':data['username'],
                'pwd':b64.encode($scope.formData['password']),
                'last_login_time':new Date(data['last_login_time']).Format("yyyy年MM月dd日 hh:mm:ss"),
                'access_token':data['access_token'],
                'token_type':data['token_type'],
                'refresh_token':data['refresh_token'],
                'expires_in':data['expires_in'],
                'scope':data['scope']};

            //计算token失效时间
            var timestamp = (new Date()).valueOf();
            userInfo['expires_time'] = timestamp+(data['expires_in']-300)*1000;//提前一点时间，防止出现遗漏

            sessionStorage.setItem('userInfo',JSON.stringify(userInfo));
            angular.element('button[type="submit"]').attr('disabled',null);
            // 页面跳转
            $state.go('main.index.detail',{reload:true});
        }).error(function(data){
            angular.element('button[type="submit"]').attr('disabled',null);
            $scope.message = data.title;
        });
    };

}]);